//
//  AsyncImageLoadDowner.m
//  Books
//
//  Created by apple on 12-3-29.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "AsyncDataLoadDowner.h"

@implementation AsyncDataLoadDowner
@synthesize isInitPlayer;
@synthesize isPlayStat;

static AsyncDataLoadDowner * audioPlayer;
+(AsyncDataLoadDowner *)GetAudioPlayer
{
    if(!audioPlayer)
    {
        audioPlayer=[[AsyncDataLoadDowner alloc]init];
        NSLog(@"GetAudioPlayer");
    }
    return audioPlayer; 
}
 
//下载其他配置
- (void)loadOtherConfigFromURL:(NSURL*)url   
{
    if (connection!=nil) {  connection=nil ; } //in case we are downloading a 2nd image
    dtype=4;
    if (data!=nil) { data =nil; }
    NSURLRequest* request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
    
    connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 
   
    NSLog(@"%@",url);
  
}

//下载配置
 - (void)loadConfigFromURL:(NSURL*)url 
{
    if (connection!=nil) {  connection=nil ; } //in case we are downloading a 2nd image
     dtype=2;
    if (data!=nil) { data =nil; }
    NSURLRequest* request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
    
    connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 
    
    NSLog(@"%@",url);
}
//下载音频
- (void)loadAudioFromURL:(NSURL*)url 
{
    if (connection!=nil) {  connection=nil ; } //in case we are downloading a 2nd image
    dtype=3;
    if (data!=nil) { data =nil; }
    NSURLRequest* request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
    
    connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 
    
   // NSLog(@"%@",url);
}
//下载图片
- (void)loadImageFromURL:(NSURL*)url  image:(UIImageView *) uimage{
    
    if (connection!=nil) {  connection=nil ; } //in case we are downloading a 2nd image
    
    if (data!=nil) { data =nil; }
    dtype=1;
    uiImage =uimage;
    
        urlfile= [self createdMD5:url.absoluteString];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    urlfile = [documentsDirectory stringByAppendingPathComponent:urlfile];
    NSLog(@"%@",urlfile);
    NSFileManager * fm =[NSFileManager defaultManager];
    
    if([fm fileExistsAtPath:urlfile]==NO )
    {
        NSLog(@"NOfileExistsAtPath");
        NSURLRequest* request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
        
        connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 
    }else {
        
        data =[NSMutableData dataWithContentsOfFile:urlfile];
        UIImage *image =[UIImage  imageWithData:data];
        uiImage.image=image;
    }
    
     
    
}

-(NSString *) createdMD5:(NSString *) signString
{
    
    const char*cStr =[signString UTF8String];
    
    unsigned char result[16];
    CC_MD5(cStr,strlen(cStr),result);
   // CC_MD5(cStr, strlen(cStr), result);
    
   NSString * strResult= [NSString stringWithFormat:
           
           @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
           
           result[0], result[1], result[2], result[3],
           
           result[4], result[5], result[6], result[7],
           
           result[8], result[9], result[10], result[11],
           
           result[12], result[13], result[14], result[15]
           
           ]; 
    
    return strResult;    
}

//the URL connection calls this repeatedly as data arrives

- (void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)incrementalData {
     
    if (data==nil) { data = [[NSMutableData alloc] initWithCapacity:2048]; }
    
    [data appendData:incrementalData];
    
}



//the URL connection calls this once all the data has downloaded

- (void)connectionDidFinishLoading:(NSURLConnection*)theConnection {
     
    if(dtype==1)
    {
        [self ProcessImage];
    }
    else if(dtype==2)
    {
        [self ProcessAdData];
    }
    else if(dtype==3)
    {
        [self ProcessAudioData];
    }
    else if(dtype==4)
    {
      [self ProcessConfigData];
    }
    connection=nil;
    
}
NSUInteger pagecount=0;
NSUInteger pageindex=0;
NSUInteger pageTotal=0;
bool isDown=false;
bool isPlaying=false;
AVAudioPlayer * player;
-(void)ProcessAudioData
{
    
    
  
          if(player==nil||!isPlaying)
    {
   
        [self PlayAudioData];
           // NSLog(@"1111加载完成，开始播放");
  
    }else {
        isDown=true;
        //NSLog(@"缓存下载完成");
    }
 
}
-(void) PlayAudioText
{
    NSString * strContents= [self  GetAudioPageText];
    if(strContents)
    {
       // NSLog(@"%@",strContents);
    NSString *soundPath= [[ NSString alloc] initWithFormat:  @"http://translate.google.cn/translate_tts?ie=UTF-8&q=%@&tl=zh-CN&total=1&idx=0&textlen=%d",[strContents  stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[strContents length]];  
    
    NSURL * url =[[NSURL alloc]  initWithString:soundPath];
    [self loadAudioFromURL:url];
    }else {
        NSLog(@"内容为nil");
    }
}
-(void) AudioPlay
{
    if(player!=nil)
    {
        [player  play];
    }
}
-(void) AudioPause
{
    if(player!=nil)
    {
        [player  pause];
    }
} NSString *bookKey ;
-(void) AudioInit
{
    pagecount=0;
    pageindex=0;
   bookKey= [DataService GetBookKey];
    pageTotal=[DataService GetPageCount:bookKey];
    [player stop];
 
    isPlaying=false;
    isDown=false;
   self.isInitPlayer=true;
   
}
-(NSString *)GetAudioPageText
{
    if(pageindex>=pageTotal)
    {
        return nil;
    }
   // NSLog(@"pageindex:%d,pageTotal:%d",pageindex,pageTotal);
   
    // NSLog(@"gBookKey%@",bookKey);
    NSDictionary * dataContents= [DataService  GetPageData:pageindex   :bookKey ];
    NSString * strContents= [dataContents objectForKey:Details];
    NSUInteger pagelen=39;
    if([strContents length]<=pagecount+pagelen)
    {
        
        pagelen=[strContents length]-pagecount;
        NSRange  range =  NSMakeRange(pagecount, pagelen);
        strContents =[strContents substringWithRange:range];
        pageindex++;
        pagecount=0;
  
    }else {
        NSRange  range =  NSMakeRange(pagecount, pagelen);
        strContents =[strContents substringWithRange:range];
        pagecount=pagecount+pagelen;
    }
   
    
    return strContents;
}
-(void)ProcessConfigData
{
    
    
    NSDictionary *myDict = [NSPropertyListSerialization propertyListFromData:data mutabilityOption:NSPropertyListImmutable format:nil errorDescription:nil];
    //save本地文件
    //resource path
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *IPDBfile = [documentsDirectory stringByAppendingPathComponent:@"config.plist"];
         [myDict writeToFile:IPDBfile atomically:true];
    [DataService SetAppsConfig:(NSMutableDictionary *)myDict];
   
}
-(void)ProcessAdData
{
 
  
    NSDictionary *myDict = [NSPropertyListSerialization propertyListFromData:data mutabilityOption:NSPropertyListImmutable format:nil errorDescription:nil];
    NSLog(@"%@",myDict);
    
    for (NSString * key in [myDict allKeys]) {
        NSDictionary * dicdata =[myDict objectForKey:key];
        int index =[[dicdata objectForKey:@"index"] intValue];
        NSDictionary * pageData =[dicdata objectForKey:@"data"];
          NSLog(@"%@",key);
        if ([key isEqualToString:@"all"]) {
            for (NSString * bookKey in [[DataService DicBooksList] allKeys]) {
              
                [DataService InsertAdPage:index book:bookKey data:pageData];    
            }
        }else {
               
             [DataService InsertAdPage:index book:key data:pageData];  
        }
    }
    
    
}
-(void)PlayAudioData
{
    NSMutableData*  playData = [[NSMutableData alloc] init];
    [playData appendData:data];
    if(player==nil)
    {
        player = [AVAudioPlayer alloc];   
    }
    
    player=[player initWithData:playData  error:nil];   
    [player prepareToPlay];   
    player.delegate=self;
    [player play];  

    isPlaying=true;
    
    [self PlayAudioText];
}
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
     // NSLog(@"播放完成");
     if (isDown) {
    NSMutableData*  playData = [[NSMutableData alloc] init];
    [playData appendData:data];
 
        [self PlayAudioData];
      //  NSLog(@"3333加载完成，开始播放%d",[playData length]);
         isDown=false;
  
     }else {
         isPlaying=false;
            //[self PlayAudioText];
     }
    
}
-(void)ProcessImage
{
    //so self data now has the complete image
    NSFileManager * fm =[NSFileManager defaultManager];
    
    if([fm fileExistsAtPath:urlfile]==NO )
    {
        [fm createFileAtPath:urlfile contents:data attributes:nil];
    }
    
    
    UIImage *image =[UIImage  imageWithData:data];
    uiImage.image=image;
    //[uiButton setBackgroundImage:image forState:UIControlStateNormal];
}
@end
